﻿using System;
using System.Linq;
using System.Linq.Expressions;
using Cost.Models;
using NBlock.Core;

namespace Cost.Services
{
    /// <summary>
    /// 品名的服务类
    /// </summary>
    public class MaterialService
    {
        #region 构造函数
        private readonly ICostRepository<Material> materialRepository;
        private readonly ICostRepository<MaterialPrice> materialPriceRepository;
        private readonly ICostRepository<V_Material> vMaterialRepository;
        public MaterialService(
            ICostRepository<MaterialPrice> materialPriceRepository,
            ICostRepository<V_Material> vMaterialRepository,
            ICostRepository<Material> materialRepository)
        {
            this.materialPriceRepository = materialPriceRepository;
            this.vMaterialRepository = vMaterialRepository;
            this.materialRepository = materialRepository;
        }
        #endregion

        public Material GetMaterial(Expression<Func<Material, bool>> filter)
        {
            if (filter != null)
                return materialRepository.Find(filter);
            else
                return null;
        }

        /// <summary>
        /// 获取指定日期的品名价格
        /// </summary>
        /// <param name="materialId"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public decimal GetMaterialPrice(string materialId, bool needProcess, DateTime? date = null)
        {
            decimal rate = 1;
            if (needProcess)
            {
                var rawMaterial = materialRepository.Find(materialId);
                materialId = rawMaterial.RawMaterialId;
                rate = rawMaterial.ProcessRate.HasValue ? rawMaterial.ProcessRate.Value : 1;
            }

            var validDate = date.HasValue ? date.Value : DateTime.Now;
            var price = materialPriceRepository
                .FindAll(p => p.MaterialId == materialId && validDate >= p.StartDate && validDate <= p.EndDate)
                .Select(p => p.Price)
                .FirstOrDefault();

            return Math.Ceiling((price / rate) * 100) / 100;
        }

        /// <summary>
        /// 获取指定供应商Id的原材料Ids
        /// </summary>
        /// <returns></returns>
        public string[] GetMaterialIdBySupplierId(string supplierId, DateTime? date)
        {
            string[] materialIds;
            if (date.HasValue)
            {
                materialIds = materialPriceRepository.FindAll(m => m.SupplierId == supplierId
                    && m.StartDate <= date.Value && m.EndDate >= date.Value).Select(m => m.MaterialId).Distinct().ToArray();
            }
            else
            {
                materialIds = materialPriceRepository.FindAll(m => m.SupplierId == supplierId)
                   .Select(m => m.MaterialId).Distinct().ToArray();
            }

            return materialIds;
        }
    }
}
